<template>
  <div class="user-management">
    <div class="search-section">
      <el-card class="search-card" shadow="never">
        <div class="search-form">
          <el-form :model="searchForm" inline>
            <el-form-item label="用户名">
              <el-input
                v-model="searchForm.username"
                placeholder="请输入用户名"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="姓名">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入姓名"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input
                v-model="searchForm.phone"
                placeholder="请输入手机号"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch" :loading="loading">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-card class="table-card" shadow="never">
        <template #header>
          <div class="table-header">
            <div class="header-left">
              <span class="table-title">用户列表</span>
              <el-tag type="info" size="small">{{ total }} 条记录</el-tag>
            </div>
            <div class="header-right">
              <el-button type="primary" @click="handleAdd" :loading="loading">
                <el-icon><Plus /></el-icon>
                新增用户
              </el-button>
              <el-button @click="handleRefresh" :loading="loading">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="userList"
          stripe
          border
          style="width: 100%"
          class="user-table"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="phone" label="手机号" width="150" />
          <el-table-column prop="role.name" label="角色" width="120">
            <template #default="{ row }">
              <el-tag v-if="row.role?.name" type="success" size="small">
                {{ row.role.name }}
              </el-tag>
              <el-tag v-else type="info" size="small">未分配</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.create_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="360" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="success" size="small" @click="handlePermission(row)">
                <el-icon><Setting /></el-icon>
                权限设置
              </el-button>
              <el-button type="warning" size="small" @click="handleRole(row)">
                <el-icon><User /></el-icon>
                角色分配
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="formRules"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="userForm.name"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="userForm.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select
            v-model="userForm.role_id"
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roleList"
              :key="role._id"
              :label="role.name"
              :value="role._id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限设置"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="permission-content">
        <div class="permission-info">
          <el-alert
            title="权限继承说明"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>• 用户权限继承自所属角色的权限</p>
              <p>• 角色权限继承自所属团队的权限</p>
              <p>• 团队权限继承自所属部门的权限</p>
              <p>• 继承的权限显示为只读状态，无法修改</p>
            </template>
          </el-alert>
        </div>
        
        <div class="permission-sections">
          <!-- 继承的权限 -->
          <div class="permission-section">
            <h4>继承的权限（只读）</h4>
            <el-tree
              :data="inheritedPermissions"
              :props="{ label: 'name', children: 'children' }"
              node-key="id"
              default-expand-all
              :disabled="true"
              class="permission-tree"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <el-icon><Lock /></el-icon>
                  <span>{{ node.label }}</span>
                  <el-tag type="info" size="small">继承</el-tag>
                </span>
              </template>
            </el-tree>
          </div>

          <!-- 用户自有权限 -->
          <div class="permission-section">
            <h4>用户自有权限</h4>
            <el-tree
              ref="permissionTreeRef"
              :data="availablePermissions"
              :props="{ label: 'name', children: 'children' }"
              node-key="id"
              show-checkbox
              default-expand-all
              :default-checked-keys="currentUserPermissions"
              class="permission-tree"
            />
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit" :loading="submitLoading">
            保存权限
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { User, Search, Refresh, Plus, Edit, Delete, Setting, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/modules/user'
import type { userInfoData, userListFormData } from '@/api/user/type'

// 用户store
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const permissionTreeRef = ref()
const userList = ref<userInfoData[]>([])
const roleList = ref<any[]>([])
const total = ref(0)
const currentUser = ref<userInfoData | null>(null)
const currentUserPermissions = ref<string[]>([])
const inheritedPermissions = ref<any[]>([])
const availablePermissions = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  username: '',
  name: '',
  phone: ''
})

// 分页配置
const pagination = reactive({
  page: 1,
  size: 10
})

// 用户表单
const userForm = reactive<userInfoData>({
  _id: '',
  username: '',
  name: '',
  password: '',
  phone: '',
  role_id: ''
})

// 表单验证规则
const formRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑用户' : '新增用户')

// 方法
const loadUserList = async () => {
  loading.value = true
  try {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 死数据
    const mockData: userInfoData[] = [
      {
        _id: '1',
        username: 'admin',
        name: '管理员',
        phone: '13800138001',
        role_id: '1',
        role: { _id: '1', name: '超级管理员' },
        permissions: ['user:read', 'user:write', 'role:read', 'role:write'],
        create_time: Date.now() - 86400000 * 30
      },
      {
        _id: '2',
        username: 'zhangsan',
        name: '张三',
        phone: '13800138002',
        role_id: '2',
        role: { _id: '2', name: '普通用户' },
        permissions: ['user:read', 'role:read'],
        create_time: Date.now() - 86400000 * 15
      },
      {
        _id: '3',
        username: 'lisi',
        name: '李四',
        phone: '13800138003',
        role_id: '3',
        role: { _id: '3', name: '部门经理' },
        permissions: ['user:read', 'role:read', 'team:read'],
        create_time: Date.now() - 86400000 * 7
      },
      {
        _id: '4',
        username: 'wangwu',
        name: '王五',
        phone: '13800138004',
        role_id: '2',
        role: { _id: '2', name: '普通用户' },
        permissions: ['user:read'],
        create_time: Date.now() - 86400000 * 3
      },
      {
        _id: '5',
        username: 'zhaoliu',
        name: '赵六',
        phone: '13800138005',
        role_id: '',
        role: null,
        permissions: [],
        create_time: Date.now() - 86400000 * 1
      }
    ]
    
    // 模拟分页
    const start = (pagination.page - 1) * pagination.size
    const end = start + pagination.size
    userList.value = mockData.slice(start, end)
    total.value = mockData.length
  } catch (error: any) {
    ElMessage.error(error.message || '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const loadRoleList = async () => {
  try {
    // 死数据 - 角色列表
    roleList.value = [
      { _id: '1', name: '超级管理员' },
      { _id: '2', name: '普通用户' },
      { _id: '3', name: '部门经理' },
      { _id: '4', name: '财务人员' },
      { _id: '5', name: '人事专员' }
    ]
  } catch (error: any) {
    ElMessage.error('获取角色列表失败')
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadUserList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    name: '',
    phone: ''
  })
  pagination.page = 1
  loadUserList()
}

const handleRefresh = () => {
  loadUserList()
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: userInfoData) => {
  isEdit.value = true
  Object.assign(userForm, row)
  dialogVisible.value = true
}

const handleDelete = async (row: userInfoData) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userStore.deleteUser(row._id)
    ElMessage.success('删除成功')
    loadUserList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const handlePermission = (row: userInfoData) => {
  currentUser.value = row
  currentUserPermissions.value = row.permissions || []
  loadUserPermissions()
  permissionDialogVisible.value = true
}

const handleRole = (row: userInfoData) => {
  ElMessage.info('角色分配功能开发中...')
}

const loadUserPermissions = () => {
  // 模拟权限树数据
  inheritedPermissions.value = [
    {
      id: 'role-inherited',
      name: '角色继承权限',
      children: [
        { id: 'user:read', name: '用户查看' },
        { id: 'role:read', name: '角色查看' },
        { id: 'team:read', name: '团队查看' }
      ]
    },
    {
      id: 'team-inherited',
      name: '团队继承权限',
      children: [
        { id: 'member:read', name: '成员查看' }
      ]
    },
    {
      id: 'department-inherited',
      name: '部门继承权限',
      children: [
        { id: 'department:read', name: '部门查看' }
      ]
    }
  ]

  availablePermissions.value = [
    {
      id: 'user-permissions',
      name: '用户管理权限',
      children: [
        { id: 'user:write', name: '用户编辑' },
        { id: 'user:delete', name: '用户删除' }
      ]
    },
    {
      id: 'personal-permissions',
      name: '个人权限',
      children: [
        { id: 'profile:edit', name: '个人资料编辑' },
        { id: 'password:change', name: '密码修改' }
      ]
    }
  ]
}

const handlePermissionSubmit = async () => {
  try {
    submitLoading.value = true
    
    // 获取选中的权限
    const checkedKeys = permissionTreeRef.value?.getCheckedKeys() || []
    const halfCheckedKeys = permissionTreeRef.value?.getHalfCheckedKeys() || []
    const allPermissions = [...checkedKeys, ...halfCheckedKeys]
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('权限设置成功')
    permissionDialogVisible.value = false
    loadUserList()
  } catch (error: any) {
    ElMessage.error('权限设置失败')
  } finally {
    submitLoading.value = false
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      await userStore.updateUser(userForm)
      ElMessage.success('更新成功')
    } else {
      await userStore.addUser(userForm)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    loadUserList()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(userForm, {
    _id: '',
    username: '',
    name: '',
    password: '',
    phone: '',
    role_id: ''
  })
  formRef.value?.clearValidate()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadUserList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadUserList()
}

const formatTime = (timestamp?: number) => {
  if (!timestamp) return '-'
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadUserList()
  loadRoleList()
})
</script>

<style scoped lang='scss'>
.user-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;



  .search-section {
    margin-bottom: 20px;
    
    .search-card {
      border-radius: 12px;
      border: none;
      
      .search-form {
        .el-form-item {
          margin-bottom: 16px;
        }
      }
    }
  }

  .table-section {
    .table-card {
      border-radius: 12px;
      border: none;
      
      .table-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .header-left {
          display: flex;
          align-items: center;
          gap: 12px;
          
          .table-title {
            font-size: 18px;
            font-weight: 600;
            color: #303133;
          }
        }
        
        .header-right {
          display: flex;
          gap: 12px;
        }
      }
      
      .user-table {
        margin-bottom: 20px;
        
        :deep(.el-table__header) {
          background-color: #fafafa;
        }
        
        :deep(.el-table__row:hover) {
          background-color: #f5f7fa;
        }
      }
      
      .pagination-wrapper {
        display: flex;
        justify-content: center;
        padding-top: 20px;
      }
    }
  }
}

.user-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.dialog-footer {
  text-align: right;
}

.permission-content {
  .permission-info {
    margin-bottom: 20px;
  }
  
  .permission-sections {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    
    .permission-section {
      h4 {
        margin-bottom: 12px;
        color: #303133;
        font-weight: 600;
      }
      
      .permission-tree {
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        padding: 12px;
        max-height: 400px;
        overflow-y: auto;
        
        .custom-tree-node {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .el-icon {
            color: #909399;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-management {
    padding: 10px;
    

    
    .search-section .search-card .search-form {
      .el-form-item {
        display: block;
        margin-bottom: 12px;
        
        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
    }
    
    .table-section .table-card .table-header {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
    }
    
    .permission-content .permission-sections {
      grid-template-columns: 1fr;
    }
  }
}
</style>
